package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private PicUploadService picUploadService;


    public boolean saveUserInfo(Map<String, String> para, String token) {
     //校验token
        User user=this.userService.queryUserBytoken(token);
        if (null==user){
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(para.get("gender"), "man")?SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setNickName(para.get("nickname"));
        userInfo.setBirthday(para.get("birthday"));
        userInfo.setCity(para.get("city"));
        int insert = this.userInfoMapper.insert(userInfo);
        return insert!=0;

    }

    public boolean saveUserLogo(MultipartFile file, String token) {
        //校验token
        User user = this.userService.queryUserBytoken(token);
        if (user == null) {
            return false;
        }
        //校验图片是否为人像,如果不是人像就返回false
        boolean b = false;
        try {
            b = this.faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //图片上传到阿里云oss
        PicUploadResult result = this.picUploadService.upload(file);
        if (StringUtils.isEmpty(result.getName())){
            //上传失败
            return false;
        }
        //把头像保存到用户的信息表中
        UserInfo userInfo=new UserInfo();
        userInfo.setLogo(result.getName());
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",user.getId() );
        return this.userInfoMapper.update(userInfo, wrapper)!=0;
    }
}
